/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ch.lab24.android.rtm;




import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;


import ch.lab24.android.rtm.provider.RTM;
import ch.lab24.android.rtm.provider.RTM.Notes;
import ch.lab24.android.rtm.provider.RTM.Tasks;


import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TaskViewActivity extends ListActivity {
    static final String ACTION = "ch.lab24.android.rtm.TASK_VIEW";

    public static final String[] TASKS_PROJECTION = new String[] {
        Tasks._ID, // 0
        Tasks.NAME, // 1
        Tasks.DUE, // 2
        Tasks.HAS_DUE, // 3
        Tasks.TAGS, // 4
        Tasks.ESTIMATE, // 5
        Tasks.POSTPONED, // 6
        Tasks.URL, // 7
    };
    public static final String[] NOTES_PROJECTION = new String[] {
        Notes._ID, // 0
        Notes.TITLE, // 1
        Notes.TEXT, // 2
        Notes.MODIFIED, // 3
    };
    
    private ViewAdapter mAdapter;
    private Uri mUri;    
    private ContentResolver mContentResolver;
    private Cursor mCursor;
    
    
    private TextView mTaskName;
    /* package */ ArrayList<ViewEntry> mDetailEntries = new ArrayList<ViewEntry>();    
    /* package */ ArrayList<ViewEntry> mNotesEntries = new ArrayList<ViewEntry>();    
    /* package */ ArrayList<ArrayList<ViewEntry>> mSections = new ArrayList<ArrayList<ViewEntry>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.screen_taskview);

        mUri = getIntent().getData();
        mContentResolver = getContentResolver();
        
        mSections.add(mDetailEntries);        
        mSections.add(mNotesEntries);  
        
        mCursor = mContentResolver.query(mUri, TASKS_PROJECTION, null, null, null);
        
        setupViews();

    }

    
    private void setupViews() {
        mTaskName = (TextView) findViewById(R.id.name);

    	if (mCursor != null) {
            // Make sure we are at the one and only row in the cursor.
            mCursor.moveToFirst();
            mTaskName.setText(mCursor.getString(mCursor.getColumnIndex(RTM.Tasks.NAME)));
            buildEntries(mCursor);  
            if (mAdapter == null) {
                mAdapter = new ViewAdapter(this, mSections);
                setListAdapter(mAdapter);
            } else {
                mAdapter.setSections(mSections, true);
            }
            
    	}
    }
    
	    
    /**
     * Build separator entries for all of the sections.
     */
    private void buildSeparators() {
        ViewEntry separator;
        
        separator = new ViewEntry();
        separator.kind = ViewEntry.KIND_SEPARATOR;
        separator.data = getString(R.string.listSeparatorDetailInformation);
        mDetailEntries.add(separator);
        
        separator = new ViewEntry();
        separator.kind = ViewEntry.KIND_SEPARATOR;
        separator.data = getString(R.string.listSeparatorNotesInformation);
        mNotesEntries.add(separator);
    }
    
    /**
     * Build up the entries to display on the screen.
     * 
     * @param taskCursor the URI for the contact being displayed
     */
    private final void buildEntries(Cursor taskCursor) {
        // Clear out the old entries
        final int numSections = mSections.size();
        for (int i = 0; i < numSections; i++) {
            mSections.get(i).clear();
        }
        buildSeparators();
        // Build the detail entries
        long dueDateData = taskCursor.getLong(taskCursor.getColumnIndex(RTM.Tasks.DUE));
        String dueDate = null;
    	SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
      	if (taskCursor.getInt(taskCursor.getColumnIndex(RTM.Tasks.HAS_DUE)) > 0)         		
      		dueDate = df.format(new Date(dueDateData));
    	else
    		dueDate = df.format(new Date(dueDateData)).substring(0, 10);
        
        if (dueDateData > 0 && dueDateData < (new Date(1000,1,1)).getTime()) {
            ViewEntry entry = new ViewEntry();
            entry.label = getString(R.string.label_due);
            entry.data = dueDate;
            entry.id = 0;
            entry.kind = ViewEntry.KIND_TASK;
            entry.uri = null;
            entry.intent = null;
            entry.maxLines = 1;
            mDetailEntries.add(entry);
        }
        String tags = taskCursor.getString(taskCursor.getColumnIndex(RTM.Tasks.TAGS));
        if (!TextUtils.isEmpty(tags)) {
            ViewEntry entry = new ViewEntry();
            entry.label = getString(R.string.label_tags);
            entry.data = tags;
            entry.id = 0;
            entry.kind = ViewEntry.KIND_TASK;
            entry.uri = null;
            entry.intent = null;
            entry.maxLines = 2;
            mDetailEntries.add(entry);
        }
        String estimate = taskCursor.getString(taskCursor.getColumnIndex(RTM.Tasks.ESTIMATE));
        if (!TextUtils.isEmpty(estimate)) {
            ViewEntry entry = new ViewEntry();
            entry.label = getString(R.string.label_estimate);
            entry.data = estimate;
            entry.id = 0;
            entry.kind = ViewEntry.KIND_TASK;
            entry.uri = null;
            entry.intent = null;
            entry.maxLines = 2;
            mDetailEntries.add(entry);
        }
        String url = taskCursor.getString(taskCursor.getColumnIndex(RTM.Tasks.URL));
        if (!TextUtils.isEmpty(url)) {
            ViewEntry entry = new ViewEntry();
            entry.label = getString(R.string.label_url);
            entry.data = url;
            entry.id = 0;
            entry.kind = ViewEntry.KIND_TASK;
            entry.uri = Uri.parse(url);
            entry.intent = null;
            entry.maxLines = 2;
            mDetailEntries.add(entry);
        }
        String postponed = taskCursor.getString(taskCursor.getColumnIndex(RTM.Tasks.POSTPONED));
        if (!TextUtils.isEmpty(url)) {
            ViewEntry entry = new ViewEntry();
            entry.label = getString(R.string.label_postponed);
            entry.data = postponed;
            entry.id = 0;
            entry.kind = ViewEntry.KIND_TASK;
            entry.uri = null;
            entry.intent = null;
            entry.maxLines = 2;
            mDetailEntries.add(entry);
        }
        
        // Build up the notes entries
        final Cursor notesCursor = mContentResolver.query( Uri.withAppendedPath(mUri, Notes.CONTENT_DIRECTORY)
        		, NOTES_PROJECTION, null
        		, null
        		, RTM.Notes.DEFAULT_SORT_ORDER);
        
        if (notesCursor != null) {
            while (notesCursor.moveToNext()) {
                String title = notesCursor.getString(notesCursor.getColumnIndex(RTM.Notes.TITLE));
                String text = notesCursor.getString(notesCursor.getColumnIndex(RTM.Notes.TEXT));
                long modified = notesCursor.getLong(notesCursor.getColumnIndex(RTM.Notes.MODIFIED));
                Date modifiedDate = new Date(modified);
	            final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	            format.setTimeZone(TimeZone.getDefault());	            

                ViewEntry entry = new ViewEntry();
                entry.label = format.format(modifiedDate) + "\n" + title + "\n" + text;
                entry.maxLabelLines = 10;
                entry.id = 0;
                entry.uri = null;
                entry.intent = null;
                entry.maxLines = 10;
                entry.isLabelOnly = true;
                entry.kind = ViewEntry.KIND_NOTE;
                mNotesEntries.add(entry);
            }
            notesCursor.close();
        }
    }
    /**
     * A basic structure with the data for a contact entry in the list.
     */
    private final static class ViewEntry extends TaskEntryAdapter.Entry {
        public int primaryIcon = -1;
        public Intent intent;
        public Intent auxIntent = null;
        public int presenceIcon = -1;
        public int actionIcon = -1;
        public String data2 = null;
        public boolean isLabelOnly = false;
        public int maxLabelLines = 1;
    }

    private static final class ViewAdapter extends TaskEntryAdapter<ViewEntry> {
        /** Cache of the children views of a row */
        static class ViewCache {
            public TextView label;
            public TextView data;
            public TextView data2;
            
            // Need to keep track of this too
            ViewEntry entry;
        }
        
        ViewAdapter(Context context, ArrayList<ArrayList<ViewEntry>> sections) {
            super(context, sections, true);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewEntry entry = getEntry(mSections, position, true); 
            View v;

            // Handle separators specially
            if (entry.kind == ViewEntry.KIND_SEPARATOR) {
                TextView separator = (TextView) mInflater.inflate(
                        R.layout.list_separator, parent, false);
                separator.setText(entry.data);
                return separator;
            }

            ViewCache views;

            // Check to see if we can reuse convertView
//            if (convertView != null) {
//                views = (ViewCache) convertView.getTag();
//                if (views != null) {
//                    ViewEntry origEntry = views.entry;
//                    if (origEntry != null) {
//                        // Check to see if the view and the entry are compatible
//                        if (entry.kind == ViewEntry.KIND_TASK
//                                && origEntry.kind != ViewEntry.KIND_TASK) {
//                            v = null;
//                        } else if (entry.kind != ViewEntry.KIND_TASK
//                                && origEntry.kind == ViewEntry.KIND_TASK) {
//                            v = null;
//                        } else if (entry.isLabelOnly != origEntry.isLabelOnly) {
//                            v = null;
//                        } else {
//                            v = convertView;
//                        }
//                    } else {
//                        v = null;
//                    }
//                } else {
//                    v = null;
//                }
//            } else {
//                v = null;
//            }
            v=null;
            // Create a new view if needed
            if (v == null && entry.kind == ViewEntry.KIND_TASK) {
                v = mInflater.inflate(R.layout.list_item_taskview, parent, false);

                // Cache the children
                views = new ViewCache();
                views.label = (TextView) v.findViewById(R.id.label);
                views.data = (TextView) v.findViewById(R.id.data);
                // label-only contact entries don't have a data view
                if (views.data != null) {
                    views.data.setCompoundDrawablePadding(3);
                }
//                views.data2 = (TextView) v.findViewById(R.id.data2);
            } else  {
                v = mInflater.inflate(R.layout.list_item_tasknoteview, parent, false);
                // Cache the children
                views = new ViewCache();
                views.label = (TextView) v.findViewById(R.id.label);
            	
            }

            // Set the tag on the view so it knows what it's displaying
            views.entry = entry;
            v.setTag(views);

            // Bind the data to the view
            bindView(v, entry);
            return v;
        }

        @Override
        protected View newView(int position, ViewGroup parent) {
            // getView() handles this
            throw new UnsupportedOperationException();
        }

        @Override
        protected void bindView(View view, ViewEntry entry) {
            final Resources resources = mContext.getResources();
            ViewCache views = (ViewCache) view.getTag();

            // Set the label
            TextView label = views.label;
            setMaxLines(label, entry.maxLabelLines);
            label.setText(entry.label);

            // Set the data
            TextView data = views.data;
            if (data != null) {
                data.setText(entry.data);
                setMaxLines(data, entry.maxLines);
            }

            // Set the left icon
            Drawable left = null;
            if (entry.primaryIcon != -1) {
                left = resources.getDrawable(entry.primaryIcon);
            } else if (entry.presenceIcon != -1) {
                left = resources.getDrawable(entry.presenceIcon);
            }

            // Set the right icon
            Drawable right = null;
            if (entry.actionIcon != -1) {
                right = resources.getDrawable(entry.actionIcon);
            }
            
            if (data != null) {
                data.setCompoundDrawablesWithIntrinsicBounds(left, null, right, null);
            }

            // Set data2 if we have it
            if (entry.kind == Contacts.KIND_ORGANIZATION) {
                views.data2.setText(entry.data2);
            }
        }

        private void setMaxLines(TextView textView, int maxLines) {
            if (maxLines == 1) {
                textView.setSingleLine(true);
                textView.setEllipsize(TextUtils.TruncateAt.END);
            } else {
                textView.setSingleLine(false);
                textView.setMaxLines(maxLines);
                textView.setEllipsize(null);
            }
        }
    }
    
}
